﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Extentions
{
    public class JwtTools
    {
        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="configuration">配置接口</param>
        /// <param name="uid">用户唯一标识</param>
        /// <returns></returns>
        public string JwtNewString(IConfiguration configuration, string uid)
        {
            //2.生成JWT
            //Header,选择签名算法
            var signingAlgorithm = SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息,下面我们放了一个用户Id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, uid),
                new Claim(ClaimTypes.Name, "Authentication:SecretKey"),//用户名
            };
            //Signature
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);
            //生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],          //发布者
                audience: configuration["Authentication:Audience"],      //接收者
                claims: claims,                                          //存放的用户信息
                notBefore: DateTime.UtcNow,                              //发布时间
                expires: DateTime.UtcNow.AddMinutes(300),                     //有效期设置为30分钟
              //expires: DateTime.UtcNow.AddSeconds(10),                     //有效期设置为30秒
                signingCredentials                                       //数字签名
            );
            //生成字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(token);

            return TokenStr;
        }


    }
}
